package edu.tec.mty.core.connection;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Connect {
	
	private int port;
	private String hostname;
	private static byte[] buffer = new byte[65507];
	private DatagramSocket socket;
	private InetAddress server;
	
	public Connect(String hostname, int port) {
		this.hostname = hostname;
		this.port = port;
	}
	
	public boolean connectToServer() {
		try {
			this.socket = new DatagramSocket();
			this.server = InetAddress.getByName(this.hostname);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
	public void sendMessage(String msg) {	
		try {
			String sended = msg + Character.toString('\0');
			byte data[] = sended.getBytes();
			DatagramPacket output = new DatagramPacket(data, data.length, server, port);
			socket.send(output);
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}
	
	public String receiveMessage() {
		String message;
		try {
			DatagramPacket input = new DatagramPacket(buffer, buffer.length);
			socket.receive(input);
			message = new String(input.getData(), 0, input.getLength() - 1);
			port = input.getPort();
		} catch (Exception e) {
			message = "Error";
			//e.printStackTrace();
		}
		return message;
	}
	
	public void close() {
		this.socket.close();
	}
	
	/*Test*/
	
	/*public static void main(String[] args) {
		connect c = new connect("192.168.1.100",6000);
		c.sendMessage("(init borregos (version 15.0))");
		String msg = c.receiveMessage();
		System.out.println(msg);
		msg = c.receiveMessage();
		System.out.println(msg);
		msg = c.receiveMessage();
		System.out.println(msg);
		msg = c.receiveMessage();
		System.out.println(msg);
		c.sendMessage("(bye)");
	}*/

}
